package com.achun.ximalayamvvm.utils

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.annotation.Nullable
import com.achun.ximalayamvvm.R

abstract class Uiloader(context: Context, @Nullable attrs: AttributeSet?, defStyleAttr: Int) :
    FrameLayout(context, attrs, defStyleAttr) {
    private var mLoadingView: View? = null
    private var mSuccessView: View? = null
    private var mNetworkErrorView: View? = null
    private var mEmptyView: View? = null
    private var mCurrentStatus: UISTATUS = UISTATUS.NONE

    //主构造初始化
    init {
        init()
    }

    constructor(context: Context, @Nullable attrs: AttributeSet?) :
            this(context, attrs, 0) {

    }

    constructor(context: Context) :
            this(context, null) {

    }

    enum class UISTATUS {
        LOADING, SUCCESS, NETWORK_ERROR, EMPTY, NONE
    }
    private fun init() {
        switchUIByCUrrentStatus()
    }
    fun updataStatus(status:UISTATUS){
       mCurrentStatus=status
       switchUIByCUrrentStatus()
   }

    private fun switchUIByCUrrentStatus() {
        //加载中
        if (mLoadingView == null) {
            mLoadingView = getLoadingView()
            addView(mLoadingView)
        }
        //根据状态设置可见
        mLoadingView!!.visibility = if (mCurrentStatus == UISTATUS.LOADING) VISIBLE else GONE

        //加载成功
        if (mSuccessView == null) {
            mSuccessView = getSuccessView()
            addView(mSuccessView)
        }
        //根据状态设置可见
        mSuccessView!!.visibility = if (mCurrentStatus == UISTATUS.SUCCESS) VISIBLE else GONE

        //页面为空
        if (mEmptyView == null) {
            mEmptyView = getEmptyView()
            addView(mEmptyView)
        }
        //根据状态设置可见
        mEmptyView!!.visibility = if (mCurrentStatus == UISTATUS.EMPTY) VISIBLE else GONE

        //网络错误
        if (mNetworkErrorView == null) {
            mNetworkErrorView = getNetworkErrorView()
            addView(mNetworkErrorView)
        }
        //根据状态设置可见
        mNetworkErrorView!!.visibility =
            if (mCurrentStatus == UISTATUS.NETWORK_ERROR) VISIBLE else GONE

    }

    fun getEmptyView(): View? {
        var view = LayoutInflater.from(context).inflate(R.layout.layout_empty, this, false)
        return view
    }

    private fun getNetworkErrorView(): View? {
        var view = LayoutInflater.from(context).inflate(R.layout.layout_network, this, false)
        view.setOnClickListener { retryOnclick() }
        return view
    }

   abstract fun retryOnclick()

    abstract fun getSuccessView(): View?

    private fun getLoadingView(): View? {
        var view = LayoutInflater.from(context).inflate(R.layout.layout_loading, this, false)
        return view
    }


}